package com.liang.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.redisson.api.RedissonClient;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import javax.management.MXBean;

/**
 * Created with Intellij IDEA
 *
 * @Auther: liangjy
 * @Date: 2022/01/06/16:48
 * @Description: 自定义模版类
 */
public class Model {
    /**
     * 自定义一个redis模板并且实现序列化
     *
     * @param factory
     * @return
     */
    @Bean
    @SuppressWarnings("all")  //作用告诉编辑器不要在编译完成后出现警告信息
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        //引入原来的redisTemplate来实现注入
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        //将工厂注入进stringTemplate中
        template.setConnectionFactory(factory);

        //采用了jackSon序列化对象
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);

        ObjectMapper om = new ObjectMapper();

        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);

        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);

        jackson2JsonRedisSerializer.setObjectMapper(om);

        //对String进行序列化
        StringRedisSerializer stringRedisTemplate = new StringRedisSerializer();

        template.setKeySerializer(stringRedisTemplate);

        template.setHashKeySerializer(stringRedisTemplate);

        template.setValueSerializer(jackson2JsonRedisSerializer);

        template.setHashKeySerializer(jackson2JsonRedisSerializer);

        template.afterPropertiesSet();

        return template;
    }

}
